<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" href="../css/public.css" />
  <link rel="stylesheet" href="../css/列表.css" />
  <title>咨询列表</title>
  <style>
    /* 设置表格单元格的样式 */
    #movie-table td {
      max-width: 150px; /* 设置单元格的最大宽度，可根据实际情况调整 */
      word-wrap: break-word; /* 允许长单词或 URL 地址换行 */
      word-break: break-all; /* 强制换行 */
    }
  </style>
</head>

<body>
  <h1>咨询列表</h1>
  <table id="movie-table" class="mt-30">
    <thead>
      <tr>
        <th><span class="fcc">咨询图片</span></th>
        <th><span class="fcc">咨询标题</span></th>
        <th><span class="fcc">咨询详情</span></th>
       
        <th><span class="fcc">操作</span></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><span class="fcc"></span></td>
        <td><span class="fcc"></span></td>
        <td class="flex aic jc-sa" id="control">
          <button class="delete-button">删除</button>
          <button class="update-button">编辑</button>
        </td>
      </tr>
    </tbody>
  </table>
  <button class="add-button">添加</button>
  <script src="../js/axios.js"></script>
  <script>
    var baseUrl = 'http://localhost:3009'
    const obj = {
      init() {
        this.byEvents();
        this.getData();
      },

      byEvents() {
        // 使用事件委托，将事件绑定到 tbody 上
        document.querySelector('tbody').addEventListener('click', (event) => {
          if (event.target.classList.contains('delete-button')) {
            alert('删除成功');
            let id = event.target.dataset.id;
            obj.del(id, event.target);
          }
        });
        document.querySelector('.add-button').onclick = () => {
          obj.add();
        }
      },
      async getData() {
        let res = await axios.get(baseUrl + "/consult/list");
        obj.render(res.data.res);
      },
      render(list) {
        let str = "";
        list.forEach((item) => {
          str += `
            <tr>
         <td><span class="fcc">${item.consultImg}</span></td>
         <td><span class="fcc">${item.title}</span></td>
        <td><span class="fcc">${item.consultDetail}</span></td>
        <td>
          <p  class="flex aic jc-sa">
              <button class="delete-button" data-id="${item._id}">删除</button>
          <button class="update-button">编辑</button>
            </p>
        </td>
      </tr>
          `;
        });
        document.querySelector('tbody').innerHTML = str;
      },

      // 删除
      async del(id, button) {
        await axios.post(baseUrl + '/consult/del', { id });
        button.closest('tr').remove();
      },

      // 添加
      async add() {
        location.href = "./add.html"
      }
    };

    obj.init();
  </script>
</body>

</html>